package cz.myslivec.slovicka.vocimport.csvparse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.jboss.seam.annotations.Logger;
import org.jboss.seam.log.Log;

import com.Ostermiller.util.CSVParser;

public abstract class ParserTemplate <O extends Object> {
	
	@Logger
	private Log log;
	
	public List<O> parseFile(String fileName) throws FileNotFoundException, IOException {
		log.info("Parsing file #0", fileName);
		File file = new File(fileName);
		FileInputStream fileStream;

		fileStream = new FileInputStream(file);
		return parseInputStream(fileStream);
	}

	public List<O> parseInputStream(InputStream inputStream) throws IOException {
		if (inputStream == null) {
			throw new IllegalArgumentException("Input stream can not be null");
		}
		CSVParser csvp = new CSVParser(inputStream, (char)';');
		return parseFileInner(csvp);
	}

	private List<O> parseFileInner(CSVParser csvp) throws IOException {
		String[] line;
		List<O> result = new ArrayList<O>(); 
		while ((line = csvp.getLine()) != null) {
			try {
				O object = processLine(csvp, line);
				if(object != null) {
					result.add(object);
				}
			} catch(IllegalStateException e) {
				log.error("Skip parsing line.");
			}
		}
		return result;
	}
	
	protected abstract O processLine(CSVParser lcsvp, String[] line);

}
